<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="10">
      <el-col :span="8">
        <div class="panel-info">
          <div class="panel-title">组织树</div>
          <div class="panel-body">
            <el-button v-if="treeData.length <= 0" v-permission='"adminDept.add"' @click="createNode(null)">创建
            </el-button>
            <div v-else class="filter-container">
              <el-input v-show="indexChangeParents.length==0" class="filter-item" style="width: 160px" clearable
                placeholder="请输入查询条件" v-model="filterText">
              </el-input>
              <div class="filter-item text-gray t-12" style="margin-bottom:0;" v-if="!filterText">
                拖动组织可调整层级和排序
              </div>
              <div class="flex1"></div>
              <div class="inline-block" v-if="!filterText">
                <template v-if="indexChangeParents.length > 0">
                  <el-button type="success" @click="saveIndex" v-permission='"adminDept.edit"' :loading="sortLoading">
                    保存排序
                  </el-button>
                  <el-button type="warning" @click="()=>{indexChangeParents=[];refreshTree()}">取消
                  </el-button>
                </template>
                <el-button type="primary" v-else @click="()=>{currentExpands=[];refreshTree()}">刷新
                </el-button>
              </div>
            </div>

            <el-tree ref="tree" :data="treeData" node-key="id" :props="{ children: 'children' }"
              :default-expand-all="false" :expand-on-click-node="false" :defaultExpandedKeys="defaultExpandedKeys"
              :filter-node-method="filterMethod" draggable @node-drop="afterDrop" @node-expand="nodeExpand"
              @node-click="nodeClick" @node-collapse="nodeCollapse">
              <div class="custom-tree-node" slot-scope="{ data }">
                <div style="flex: 1; overflow: hidden">
                  <i v-if="data.children && data.children.length > 0" class="fa fa-folder text-blue t-14"></i>
                  <i v-else class="fa fa-folder-o text-blue t-14"></i>
                  <span class="text-bold ml-10">[{{ data.dept_code }}] {{ data.dept_name }}</span>
                  <span class="ml-5 text-gray">{{data.manager?'负责人:'+data.manager:''}}</span>
                </div>
                <div>
                  <i class="fa fa-pencil-square-o text-blue pl-10" v-permission='"adminDept.edit"' aria-hidden="true"
                    title="编辑" @click.prevent.stop="editNode(data)"></i>
                  <i class="fa fa-toggle-right text-green pl-10" v-permission='"adminDept.add"' aria-hidden="true"
                    title="创建平级" @click.prevent.stop="createNode(data)"></i>
                  <i class="fa fa-toggle-down text-purple pl-10" v-permission='"adminDept.add"' aria-hidden="true"
                    title="创建下级" @click.prevent.stop="createChildNode(data)"></i>
                  <i class="fa fa-trash-o text-red pl-10" v-permission='"adminDept.delete"' aria-hidden="true"
                    title="删除" @click.prevent.stop="removeNode(data)"></i>
                </div>
              </div>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="panel-info">
          <div class="panel-title">用户列表</div>
          <div class="panel-body">
            <User style="padding:0" class="UserSearch" ref="user"></User>
          </div>
        </div>
      </el-col>
    </el-row>

    <zFormDialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submitNode"
      :submitLoading="submitLoading" :visible.sync="editNodeFormVisible"></zFormDialog>
  </div>
</template>

<script>
import { generateTree, expendsTree, dateTools } from '@/utils'
import commonMixin from '@/views/_common/mixin'
import User from './user.vue'

export default {
  mixins: [commonMixin],
  components: { User },
  name: 'adminDept',
  data: function () {
    return {
      name: '组织',
      api: this.$api.organize,
      sortLoading: false,
      currentId: 0,
      treeData: [],
      data: {},
      initData: {
        parent_id: 0,
        seq: 9999,
        org_roles: [],
      },
      formProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
      },
      fields: [
        { title: '组织代码', key: 'dept_code', required: true },
        { title: '组织名称', key: 'dept_name', required: true },
        {
          title: '负责人',
          key: 'manager',
          name: 'select',
          options: [],
          props: {
            filterable: true,
            remote: true,
            remoteMethod: null,
          },
        },
        {
          title: '角色',
          key: 'org_roles',
          name: 'select',
          props: {
            options: [],
            filterable: true,
            multiple: true,
            clearable: true,
          },
        },
      ],
      editNodeFormVisible: false,
      indexChangeParents: [],
      filterText: '',
      currentExpands: [],
      defaultExpandedKeys: [],
    }
  },
  methods: {
    getUserOptions(query) {
      this.setFieldOptions('manager', [])
      if (query) {
        this.$request(this.$api.user + 'getlist', { size: 50, page: 1, queryString: query })
          .then((r) => {
            this.setFieldOptions('manager', r.list, 'userid', ['username', 'userid'])
          })
          .catch(() => {})
      }
    },
    singleUserOptions(v) {
      this.setFieldOptions('manager', [])
      if (v) {
        this.$request(this.$api.user + 'getlist', {
          queryString: v,
        })
          .then((r) => {
            this.setFieldOptions('manager', r.list, 'userid', ['username', 'userid'])
          })
          .catch(() => {})
      }
    },
    editNode(data) {
      this.pageLoading = true
      this.currentId = data.id
      this.$request(this.api + 'getByid?id=' + data.id)
        .then((r) => {
          this.data = r
          this.singleUserOptions(r.manager)
          this.editNodeFormVisible = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    createNode(data) {
      if (data) {
        this.data = { ...this.initData }
        this.data.parent_id = data.parent_id
      } else {
        this.data = { ...this.initData }
      }
      this.editNodeFormVisible = true
    },
    createChildNode(data) {
      this.data = { ...this.initData }
      this.data.parent_id = data.id
      this.editNodeFormVisible = true
    },
    submitNode() {
      const data = Object.assign({}, this.data)
      delete data.Children
      let check = this.validataData(this.fields, data)
      if (!check) return
      this.submitLoading = true
      console.log(data, 'data')
      this.$request(this.api + (data.id ? 'edit' : 'add'), { ...data }, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message.success('操作成功')
          this.editNodeFormVisible = false
          this.refreshTree()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    removeNode(data) {
      let that = this
      this.$confirm('确定要删除这条记录?').then(() => {
        this.pageLoading = true
        this.$request(this.api + 'delete?id=' + data.id, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message.success('操作成功')
            this.refreshTree()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    saveIndex() {
      var tmp = expendsTree(this.treeData, 'children')
      var data = tmp
        .filter((i) => this.indexChangeParents.includes(i.parent_id))
        .map((i, index) => ({
          id: i.id,
          seq: index,
          parent_id: i.parent_id,
        }))
      this.sortLoading = true
      const url = this.api + 'sort'
      this.$request(url, data, 'post')
        .then((r) => {
          this.sortLoading = false
          this.$message.success('操作成功')
          this.indexChangeParents = []
          this.refreshTree()
        })
        .catch(() => {
          this.sortLoading = false
        })
    },
    afterDrop(i, j, type) {
      if (type == 'inner') {
        i.data.parent_id = j.data.id
      } else {
        i.data.parent_id = j.data.parent_id
      }
      console.log(i, j, type)
      this.indexChangeParents.push(i.data.parent_id)
    },
    filterMethod(value, data) {
      if (!value) return true
      return data.dept_code.includes(value) || data.dept_name.includes(value)
    },
    refreshTree() {
      this.pageLoading = true
      this.$request(this.api + 'getAllList')
        .then((r) => {
          this.treeData = r
          this.defaultExpandedKeys = [...this.currentExpands]
          this.pageLoading = false
        })
        .catch((e) => {
          this.pageLoading = false
        })
    },
    nodeExpand(data) {
      this.currentExpands.push(data.id)
    },
    nodeCollapse(data) {
      let i = this.currentExpands.findIndex((x) => x == data.id)
      if (i != -1) this.currentExpands.splice(i, 1)
    },
    // ***************** 新增位置 *********************
    //
    nodeClick(data) {
      let arr = [data.id]
      this.$request(this.$api.organize + 'getList?size=200' + '&queryString=' + '').then((r) => {
        this.formateNodeClick(arr, data, r.list)
        arr.reverse()
        this.changeQueryString(arr)
      })
    },
    formateNodeClick(arr, data, list) {
      if (data.parent_id != 0) {
        let index = list.findIndex((el) => el.id == data.parent_id)
        arr.push(list[index].id)
        this.formateNodeClick(arr, list[index], list)
      }
    },
    changeQueryString(arr) {
      this.$nextTick(() => {
        this.$refs.user.query.deptid = arr
        this.$refs.user.research()
      })
    },
  },
  created: function () {
    this.refreshTree()
    this.$request(this.$api.role + 'getlist', { size: 9999 })
      .then((r) => {
        this.setFieldOptions('org_roles', r.list, 'id', ['role_code', 'role_name'])
      })
      .catch(() => {})

    this.getFieldConfig('manager').props.remoteMethod = this.getUserOptions
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    data: function (val) {},
  },
}
</script>

<style lang='scss' scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 12px;
  justify-content: space-between;
  padding-right: 8px;
  overflow: hidden;
}
.disabled {
  cursor: not-allowed;
}
::v-deep .el-dropdown {
  font-size: inherit !important;
}

// .UserSearch ::v-deep .filter-container {
//   justify-content: flex-end;
// }
</style>
